package org.koyad.portal.tags.html;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.koyad.portal.annotations.TagCordinates;
import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.exceptions.ErrorCodes;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.tags.Attribute;
import org.koyad.portal.tags.AbstractTag;
import org.koyad.portal.utils.LogUtils;

@TagCordinates (
	uri = FrameworkConstants.HTML5_NAMESPACE,
	localName = "form"
)
public class FormTag extends AbstractTag {
	
	private static final LogUtils LOGGER = LogUtils.getLogger(FormTag.class);
	
	private static final String ACTION_ATTRIBUTE_NAME = "action";

	@SuppressWarnings("unchecked")
	@Override
	public void postInit() {
			
		//validate action attribute
		PistonContext pistonCtx = PistonContext.getContext();
		Map<String, String> actions = (Map<String, String>)pistonCtx.getApplication().getAttribute(FrameworkConstants.PISTON_ACTIONS);
		String actionClass = actions.get(getAttributeValue(ACTION_ATTRIBUTE_NAME));
		
		try {	
				Class.forName(actionClass);
		} catch (ClassNotFoundException e) {
			LOGGER.logException(e);
			throw new FrameworkException(ErrorCodes.FWKTV001);
		}
		
		/* ======= Hidden input field for action name ====== */
		InputTag hiddenAction = new InputTag();
		//Attributes
		List<Attribute> attributes = new ArrayList<Attribute>();
		attributes.add(new Attribute("type", "hidden"));
		attributes.add(new Attribute("name", FrameworkConstants.PISTON_FWK_ACTION));
		attributes.add(new Attribute("value", getAttributeValue(ACTION_ATTRIBUTE_NAME)));
		
		hiddenAction.setAttributes(attributes);
		hiddenAction.setPreStartTagText(_preStartTagText + "\t");

		addChild(hiddenAction);
		
		/* ======= Hidden input field for tile id ======= */
		String currentTileId = PistonContext.getContext().getViewRoot().getCurrentTileId();
		if(null != currentTileId) {
			InputTag hiddenTileID = new InputTag();
			//Attributes
			attributes = new ArrayList<Attribute>();
			attributes.add(new Attribute("type", "hidden"));
			attributes.add(new Attribute("name", FrameworkConstants.PISTON_TILE_ID));
			attributes.add(new Attribute("value", currentTileId));
			
			hiddenTileID.setAttributes(attributes);
			hiddenTileID.setPreStartTagText(_preStartTagText + "\t");
	
			addChild(hiddenTileID);
		}
		
		//change the value of action attribute
		StringBuffer buffer = new StringBuffer(PistonContext.getContext().getRequest().getContextPath());
		buffer.append("/");
		buffer.append(FrameworkConstants.PISTON_FWK);
		getAttribute("action").setValue(buffer.toString());
		
	}
	
}
